import qs from 'querystring'

/**
 * 格式化用户需要的 cookie
 */
const normalizeUserCookie = (cookies = '') => {
  if (cookies) {
    let output = []
    const input = (cookies.match(/([\w\-.]*)=([^\s=]+);/g) || [])
    input.forEach((str) => {
      if (str !== 'Path=/;') {
        output.push(str)
      }
    })
    wx.setStorageSync('LDSESSIONID', output.join(' '))
  }
}

export const getStorage = theKey => new Promise((resolve, reject) => {
  wx.getStorage({
    key: theKey,
    success (res) {
      resolve(res.data)
    },
    fail (e) {
      reject(e)
    }
  })
})

export const setStorage = (theKey, theValue) => new Promise((resolve, reject) => {
  wx.setStorage({
    key: theKey,
    data: theValue,
    success () {
      resolve()
    },
    fail (e) {
      reject(e)
    }
  })
})

export const getLocation = () => new Promise((resolve) => {
  wx.getLocation({
    success ({ latitude, longitude, speed, accuracy }) {
      resolve({ latitude, longitude, speed, accuracy })
    },
    fail () {
      resolve({
        latitude: -999,
        longitude: -999
      })
    }
  })
})

export const removeStorage = theKey => new Promise((resolve, reject) => {
  wx.removeStorage({
    key: theKey,
    success (res) {
      resolve(res.data)
    },
    fail (e) {
      reject(e)
    }
  })
})

export const clearStorage = () => new Promise((resolve, reject) => {
  try {
    wx.clearStorageSync()
    resolve()
  } catch (e) {
    reject(e)
  }
})

export const login = () => new Promise((resolve, reject) => {
  wx.login({
    success (res) {
      resolve(res)
    },
    fail (e) {
      reject(e)
    }
  })
})

export const request = obj => new Promise((resolve, reject) => {
  if (!(obj.noToast || (obj.data && obj.data.noToast))) {
    wx.showToast({ title: obj.toastText || '处理中...', icon: 'loading', duration: 5000 })
  }
  obj.data && delete obj.data.noToast
  if (obj.method === 'POST') {
    wx.request({
      url: obj.url,
      data: qs.stringify(obj.data),
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'cookie': wx.getStorageSync('LDSESSIONID'),
        ...obj.header
      },
      method: obj.method,
      success (res) {
        wx.hideToast()
        normalizeUserCookie(res.header['Set-Cookie'])
        if (res && res.data && res.data.result) {
          resolve(res.data)
        } else {
          wx.showModal({
            title: '提示',
            content: (res && res.data && res.data.msg) || '系统繁忙，请稍后再试',
            showCancel: false
          })
          reject(new Error())
        }
      },
      fail (e) {
        wx.hideToast()
        wx.showModal({
          title: '提示',
          content: '网络异常',
          showCancel: false
        })
        reject(e)
      }
    })
  } else {
    wx.request({
      url: obj.url,
      data: obj.data,
      header: {
        'cookie': wx.getStorageSync('LDSESSIONID'),
        ...obj.header
      },
      method: obj.method,
      success (res) {
        wx.hideToast()
        normalizeUserCookie(res.header['Set-Cookie'])
        resolve(res.data)
      },
      fail (e) {
        wx.hideToast()
        console.log(e)
        reject(e)
      }
    })
  }
})

export const getUserInfo = () => new Promise((resolve, reject) => {
  wx.getUserInfo({
    success (res) {
      resolve(res)
    },
    fail (e) {
      console.log(e)
      reject(e)
    }
  })
})

export const uploadFile = obj => new Promise((resolve, reject) => {
  wx.showToast({ title: '图片上传中...', icon: 'loading', duration: 15000 })
  wx.uploadFile({
    url: obj.url,
    filePath: obj.filePath,
    name: obj.name,
    formData: obj.formData,
    success (res) {
      wx.hideToast()
      resolve(res)
    },
    fail (e) {
      wx.hideToast()
      console.log(e)
      reject(e)
    },
    complete () {
      wx.hideToast()
    }
  })
})

export const downloadFile = obj => new Promise((resolve, reject) => {
  wx.showToast({ title: obj.toastText || '图片下载中...', icon: 'loading', duration: 15000 })
  wx.downloadFile({
    url: obj.url,
    header: obj.header,
    success (res) {
      wx.hideToast()
      resolve(res)
    },
    fail (e) {
      wx.hideToast()
      console.log(e)
      reject(e)
    },
    complete () {
      wx.hideToast()
    }
  })
})

export const saveImageToPhotosAlbum = obj => new Promise((resolve, reject) => {
  wx.saveImageToPhotosAlbum({
    filePath: obj.filePath,
    success (res) {
      wx.showToast({
        title: '保存成功'
      })
      resolve(res)
    },
    fail (e) {
      wx.showModal({
        title: '提示',
        content: '保存失败，请重试',
        showCancel: false
      })
      reject(e)
    }
  })
})

export const chooseAddress = () => new Promise((resolve, reject) => {
  wx.chooseAddress({
    success (res) {
      resolve(res)
    },
    fail (e) {
      console.log(e)
      reject(e)
    }
  })
})

export const getSetting = () => new Promise((resolve, reject) => {
  wx.getSetting({
    success (res) {
      resolve(res)
    },
    fail (e) {
      console.log(e)
      reject(e)
    }
  })
})

export default {
  getStorage,
  setStorage,
  getLocation,
  removeStorage,
  clearStorage,
  login,
  request,
  getUserInfo,
  uploadFile,
  chooseAddress,
  getSetting
}
